const express = require('express');
const router = express.Router();
const Task = require('../models/Task');
const auth = require('../middleware/auth');

// 获取用户的所有任务
router.get('/', auth, async (req, res) => {
  try {
    const tasks = await Task.find({ userId: req.user.id });
    
    // 为每个任务添加下次可完成时间信息
    const tasksWithNextTime = tasks.map(task => {
      const taskObj = task.toObject();
      if (task.completed) {
        taskObj.nextAvailableAt = task.getNextAvailableTime();
      }
      return taskObj;
    });
    
    res.json(tasksWithNextTime);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// 创建新任务
router.post('/', auth, async (req, res) => {
  try {
    const task = new Task({
      ...req.body,
      userId: req.user.id
    });
    const newTask = await task.save();
    res.status(201).json(newTask);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// 完成任务
router.patch('/:id/complete', auth, async (req, res) => {
  try {
    const task = await Task.findOne({ _id: req.params.id, userId: req.user.id });
    if (!task) {
      return res.status(404).json({ message: '任务不存在' });
    }

    if (!task.canComplete()) {
      const nextTime = task.getNextAvailableTime();
      return res.status(400).json({ 
        message: `任务尚未到可完成时间，请等待至 ${nextTime.toLocaleString('zh-CN')}`,
        nextAvailableAt: nextTime
      });
    }

    await task.complete();
    
    // 返回更新后的任务信息，包括下次可完成时间
    const updatedTask = task.toObject();
    updatedTask.nextAvailableAt = task.getNextAvailableTime();
    
    res.json(updatedTask);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// 删除任务
router.delete('/:id', auth, async (req, res) => {
  try {
    const task = await Task.findOne({ _id: req.params.id, userId: req.user.id });
    if (!task) {
      return res.status(404).json({ message: '任务不存在' });
    }
    await task.deleteOne();
    res.json({ message: '任务已删除' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router; 